var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');

var shasum = crypto.createHash('sha1');
//shasum.update("c518f228e213c172");
shasum.update("db3d38fe4d3a97e5");
var result = shasum.digest('hex');
var code = 0;

var target = '';
/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send(result);
});

router.get('/target', function (req, res, next) {
    if (target) {
        res.send(target);
        target = '';
    } else {
        res.send('');
    }

});

router.post('/', function (req, res, next) {
    // console.log(req.params);
    // console.log(req.body);
    // console.log(req.body.Msg.Content);
    var content = req.body.Msg.Content;
    // var encoded = new Buffer(content).toString('base64');
    // base64解码
    var decoded = new Buffer(content, 'base64').toString();
    // console.log(decoded);

    var decodedSessionParams = new Buffer(req.body.SessionParams, 'base64').toString();
    // console.log(decodedSessionParams);

    req.body.SessionParams = JSON.parse(decodedSessionParams);
    req.body.Msg.Content = JSON.parse(decoded);

    var preWriteString = JSON.stringify(req.body) + '\n';

    fs.appendFile(path.join(__dirname, '../post.txt'), preWriteString, function () {
        console.log('write into file');
    });


    var name = '';
    var age = '';

    var intent = JSON.parse(decoded).intent;
    // console.log("intent.text = " + intent.text);
    if (intent.text !== undefined) {

        if (intent.category == "PHYSICS.navigation_poi") {
            name = intent.semantic[0].slots[0].value;
            target = name;
            req.body.Msg.Content.intent.answer = {'text': "即将为您导航到" + name};

            res.json(req.body.Msg.Content);
        }

    }
    res.json(req.body.Msg.Content);
    // console.log("code = "+code);

    // res.json(req.body.Msg.Content);
});

module.exports = router;
